package com.cennavi.minemapdemo.activity.offline;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.adapter.OfflineDownAdapter;
import com.cennavi.minemapdemo.offline.OfflinDownItem;
import com.cennavi.minemapdemo.offline.OfflinProv;
import com.cennavi.minemapdemo.offline.OfflineListenerAdpter;
import com.cennavi.minemapdemo.offline.OfflineUtil;
import com.minedata.minemap.offline.OfflineDataListener;
import com.minedata.minemap.offline.OfflineDataManager;
import com.minedata.minemap.offline.OfflineRecord;
import com.minedata.minemap.offline.OfflineRecordInfo;

import java.util.ArrayList;
import java.util.List;

public class OfflineMapActivity extends BaseActivty {



    //下载管理类
    private OfflineDataManager mOfflineDataManager;
    private Context mContext;
    //基础数据下载完成
    private boolean isDownBaseDataOver = false;

    private RecyclerView recyclerView;
    private OfflineDownAdapter offlineDownAdapter = null;
    private List<OfflinDownItem> data = new ArrayList<>();
    //	离线地图正式版本 官网02
    public static String SERVER_DATA_JSON_ROOT_URL="https://minedata.cn/lbsservice/mapdownload/datastore.json";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navi_download);
        mContext = this;
        //获取下载管理对象
        mOfflineDataManager = OfflineDataManager.getInstance();
        //初始化控件
        initRecyclerView();
        initE();



    }

    private void initE() {
        OfflineDataListener listener = new OfflineDataListener() {
            @Override
            public void onOfflineDataEvent(int event, int err, Object data) {
                String msg = null;
                OfflineRecordInfo item = null;
                switch (event) {
                    case OfflineDataManager.Event.INIT:
                        //获取下载信息对象
                        OfflineRecord[] datas = mOfflineDataManager.getOfflineRecords();
                        getAllOfflineData(datas);
                        offlineDownAdapter.notifyDataSetChanged();
                        break;
                    case OfflineDataManager.Event.START:
                        item = (OfflineRecordInfo) data;
                        String name = changCityItemState(item, OfflineDataManager.Status.START);
                        offlineDownAdapter.notifyDataSetChanged();
                        break;
                    case OfflineDataManager.Event.PAUSE://暂停
                        item = (OfflineRecordInfo) data;
                        changCityItemState(item, OfflineDataManager.Status.PAUSE);
                        break;
                    case OfflineDataManager.Event.REMOVE://删除
                        item = (OfflineRecordInfo) data;
                        changCityItemState(item, OfflineDataManager.Status.INIT);
                        offlineDownAdapter.notifyDataSetChanged();
                        break;
                    case OfflineDataManager.Event.TRACKING:
                        //实时跟踪下载进度,修改下载进度条和下载比例等信息
                        item = (OfflineRecordInfo) data;
                        upDoingItemState(item);
                        break;
                    case OfflineDataManager.Event.FAIL:
                        switch (err) {
                            case OfflineDataManager.Error.NONE:
                                //无错误
                                break;
                            case OfflineDataManager.Error.NET_ERROR:
                                //网络异常
                                msg = "网络异常";
                                break;
                            case OfflineDataManager.Error.SDCARD_ERROR:
                                //访问异常
                                msg = "没有sdcard";
                                break;
                        }
                        break;
                    case OfflineDataManager.Event.COMPLETED:
                        //跟踪正常信息，获取数据变化
                        item = (OfflineRecordInfo) data;
                        String nameF = changCityItemState(item, OfflineDataManager.Status.COMPLETED);
                        addFinish(nameF);
                        offlineDownAdapter.notifyDataSetChanged();
                        break;
                }
                if (msg != null) {
                    showToast(msg);
                }
            }
        };
        mOfflineDataManager.init(mContext, listener,  SERVER_DATA_JSON_ROOT_URL);
//        mOfflineDataManager.init(mContext, listener,  SERVER_DATA_JSON_ROOT_URL,自定义地址); 将来2.0.7 版本会提供


    }

    private void initRecyclerView() {

        recyclerView = findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        offlineDownAdapter = new OfflineDownAdapter(data,this);
        offlineDownAdapter.addListener(new OfflineListenerAdpter() {
            @Override
            public void onItemClick(OfflinDownItem bean) {
                if (!bean.getName().equals("基础数据") && isDownBaseDataOver == false) {//没有下载基础数据 先下载基础数据
                    showToast("基础数据未下载完成之前，请勿下载其他数据", 1);
                    OfflinDownItem item = findItemsDateByName("基础数据");
                    if (item != null) {
                        if (item.isUpdate()) {
                            mOfflineDataManager.update(item.getDataId());
                        } else {
                            mOfflineDataManager.start(item.getDataId());
                        }
                    }
                    return;
                }

                switch (bean.getState()) {
                    case OfflineDataManager.Status.START:
                        judgeBaseDataPase(bean);
                        mOfflineDataManager.pause(bean.getDataId());
                        break;
                    case OfflineDataManager.Status.UPDATE:
                        judgeBaseDataPase(bean);
                        mOfflineDataManager.pause(bean.getDataId());
                        break;
                    case OfflineDataManager.Status.COMPLETED:
                        break;
                    case OfflineDataManager.Status.UPDATECOMPLETED:
                        break;
                    case OfflineDataManager.Status.PAUSE:
                        if (bean.isUpdate()) {
                            mOfflineDataManager.update(bean.getDataId());
                        } else {
                            mOfflineDataManager.start(bean.getDataId());
                        }
                        break;
                    default:
                        if (bean.isUpdate()) {
                            mOfflineDataManager.update(bean.getDataId());
                        } else {
                            mOfflineDataManager.start(bean.getDataId());
                        }
                        break;

                }
            }

            @Override
            public void onItemLongClick(OfflinDownItem bean) {
                super.onItemLongClick(bean);
            }


        });
        recyclerView.setAdapter(offlineDownAdapter);
    }

    private ArrayList<OfflinDownItem> doings = new ArrayList<>();
    //判断是否暂停的是基础数据  如果是 先暂停其他 再暂停
    private void judgeBaseDataPase(OfflinDownItem bean) {
        if (bean.getName().equals("基础数据")) {
            //暂停其他
            if (doings != null && doings.size() > 0) {
                for (OfflinDownItem downItem : doings) {
                    if (!downItem.getName().equals("基础数据")) {
                        mOfflineDataManager.pause(downItem.getDataId());
                    }
                }
            }
        }
    }

    private OfflinDownItem findItemsDateByName(String name) {
        if (data != null && data.size()>0)
            for (OfflinDownItem downItem : data) {

                if (downItem.getName().equals(name)) {
                    return downItem;
                }
                if (downItem.getChildBean() != null) {
                    for (OfflinDownItem downChild : downItem.getChildBean()) {
                        if (downChild.getName().equals(name)) {
                            return downChild;
                        }
                    }
                }
            }
        return null;
    }


    private void getAllOfflineData(OfflineRecord[] datas) {
        if (datas == null || datas.length == 0) {
            return;
        }
        List<OfflinProv> provList = new ArrayList<>();
        for (OfflineRecord data : datas) {
            try {
                if (data.getOfflineRecordInfos() != null && data.getOfflineRecordInfos().length > 0) {
                    //数据合并
                    OfflineRecordInfo info = data.getOfflineRecordInfos()[0];
                    String provName = "全国";
                    OfflinDownItem item = new OfflinDownItem();
                    item.setName(data.getName());
                    item.setSize(info.getFileSize());
                    item.setDownloadSize(info.getDownSize());
                    item.setState(info.getStatus());
                    item.setDataId(info.getDataId());
                    item.setUpdate(info.isUpdate());
                    if (info.getStatus() == OfflineDataManager.Status.COMPLETED ||
                            info.getStatus() == OfflineDataManager.Status.UPDATECOMPLETED) {
                        addFinish(data.getName());
                    }

                    if (provList.size() > 0) {
                        boolean addover = false;
                        for (OfflinProv pone : provList) {
                            if (provName != null && provName.equals(pone.name)) {
                                pone.dates.add(item);
                                addover = true;
                                break;
                            }
                        }
                        if (!addover) {
                            OfflinProv provone = new OfflinProv();
                            provone.name = provName;
                            provone.dates = new ArrayList<>();
                            provone.dates.add(item);
                            provList.add(provone);
                        }
                    } else {
                        OfflinProv provone = new OfflinProv();
                        provone.name = provName;
                        provone.dates = new ArrayList<>();
                        provone.dates.add(item);
                        provList.add(provone);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //区域全部数据
        if (provList.size() > 0) {
            try {
                data.clear();
                for (OfflinProv one : provList) {
                    OfflinDownItem pat = new OfflinDownItem();
                    if ("全国".equals(one.name)) {
                        for (OfflinDownItem child : one.dates) {
                            pat = child;
                            pat.setType(OfflineUtil.PARENT_ITEM_NO_CHILD);
                            data.add(pat);
                        }
                    } else if (one.dates != null && one.dates.size() > 1) {
                        for (OfflinDownItem child : one.dates) {
                            child.setType(OfflineUtil.CHILD_ITEM);
                            pat.addChildBean(child);
                        }
                        pat.setName(one.name);
                        pat.setType(OfflineUtil.PARENT_ITEM);
                        data.add(pat);
                    } else if (one.dates.size() == 1) {
                        pat = one.dates.get(0);
                        pat.setType(OfflineUtil.PARENT_ITEM_NO_CHILD);
                        data.add(pat);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void addFinish(String name) {
        if (TextUtils.isEmpty(name)) {
            return;
        }
        if (name.equals("基础数据")) {
            isDownBaseDataOver = true;
        }
    }

    //改变列表中其中一个状态
    private String changCityItemState(OfflineRecordInfo bean, int state) {
        String name = null;
        for (OfflinDownItem downItem : data) {
            if (bean.getDataId().equals(downItem.getDataId())) {
                downItem.setState(state);
                name = downItem.getName();
                break;
            }
        }
        offlineDownAdapter.notifyDataSetChanged();
        return name;
    }

    private void upDoingItemState(OfflineRecordInfo bean) {
        boolean refresh = false;
        if (data != null && data.size() > 0)
            for (OfflinDownItem downItem : data) {
                if (downItem.getDataId().equals(bean.getDataId())) {
                    int oldp = downItem.getPrNumber();
                    downItem.setState(bean.getStatus());
                    downItem.setDownloadSize(bean.getDownSize());
                    int newP = downItem.getPrNumber();
                    if (newP > oldp) {
                        refresh = true;
                    }
                }
            }
        if (refresh) {
            offlineDownAdapter.notifyDataSetChanged();
        }
    }


}
